package com.gs.netty.support.resolver;


import com.gs.netty.core.resolver.args.HandlerMethodArgumentResolver;
import com.gs.netty.websocket.remoting.req.NativeWebSocketRequest;
import com.gs.netty.websocket.remoting.req.Request;
import com.gs.netty.websocket.remoting.resp.Response;
import org.springframework.core.MethodParameter;

/**
 * 请求 Channel 参数解析器
 */

public class RequestResponseMethodArgumentResolver implements HandlerMethodArgumentResolver<NativeWebSocketRequest> {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {

        Class<?> parameterType = parameter.getParameterType();
        return Object.class != parameterType && (parameterType.isAssignableFrom(Request.class )||
                parameterType.isAssignableFrom(Response.class));
    }
    @Override
    public Object resolveArgument(MethodParameter parameter, NativeWebSocketRequest request) throws Exception {
        Class<?> paramType = parameter.getParameterType();
        if (Request.class.isAssignableFrom(paramType)) {
            if (!paramType.isInstance(request)) {
                throw new IllegalStateException(
                        "Current request is not of type [" + paramType.getName() + "]: " + request);
            }
            return request.getNativeRequest();
        }
        if (Response.class.isAssignableFrom(paramType)) {
            if (!paramType.isInstance(request.getNativeResponse())) {
                throw new IllegalStateException(
                        "Current request is not of type [" + paramType.getName() + "]: " + request);
            }
            return request.getNativeResponse();
        }

        throw new UnsupportedOperationException("Unknown parameter type: " + paramType.getName());
    }
}
